package org.example.demo.controller;

import org.example.demo.service.GoodsService;
import org.example.demo.model.GoodsInfo;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.example.demo.service.TransferTimeService;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TransferTimeService transferTimeService;

    /**
     * 添加商品
     */
    @PostMapping("/add")
    public Map<String, Object> addGoods(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String name = params.get("name");
            String description = params.get("description");
            String account = params.get("account"); // 获取用户指定的账户
            
            TransactionReceipt receipt;
            if (account != null && !account.isEmpty()) {
                receipt = goodsService.addGoods(name, description, account);
            } else {
                receipt = goodsService.addGoods(name, description);
            }
            
            // 从日志中提取商品ID
            BigInteger goodsId = goodsService.getGoodsIdFromAddEvent(receipt);
            
            result.put("success", true);
            result.put("txHash", receipt.getTransactionHash());
            result.put("goodsId", goodsId.toString());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加商品失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 查询商品
     */
    @GetMapping("/get")
    public Map<String, Object> getGoods(@RequestParam String goodsId, @RequestParam(required = false) String account) {
        Map<String, Object> result = new HashMap<>();
        try {
            GoodsInfo goods;
            if (account != null && !account.isEmpty()) {
                goods = goodsService.getGoods(new BigInteger(goodsId), account);
            } else {
                goods = goodsService.getGoods(new BigInteger(goodsId));
            }
            
            result.put("success", true);
            result.put("goods", goods);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询商品失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 更新商品
     */
    @PostMapping("/update")
    public Map<String, Object> updateGoods(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            BigInteger goodsId = new BigInteger(params.get("goodsId"));
            String name = params.get("name");
            String description = params.get("description");
            String account = params.get("account"); // 获取用户指定的账户
            
            TransactionReceipt receipt;
            if (account != null && !account.isEmpty()) {
                receipt = goodsService.updateGoods(goodsId, name, description, account);
            } else {
                receipt = goodsService.updateGoods(goodsId, name, description);
            }
            
            result.put("success", true);
            result.put("txHash", receipt.getTransactionHash());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新商品失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 转移商品
     */
    @PostMapping("/transfer")
    public Map<String, Object> transferGoods(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            BigInteger goodsId = new BigInteger(params.get("goodsId"));
            String toAddress = params.get("to");
            String account = params.get("account"); // 操作账户
            String currentOwner = params.get("currentOwner"); // 添加当前所有者地址参数
            
            System.out.println("收到转移商品请求：");
            System.out.println("  - 商品ID: " + goodsId);
            System.out.println("  - 接收者地址: " + toAddress);
            System.out.println("  - 操作账户: " + account);
            System.out.println("  - 当前所有者: " + currentOwner);
            
            TransactionReceipt receipt;
            if (account != null && !account.isEmpty()) {
                // 使用前端提供的当前所有者信息进行转移
                receipt = goodsService.transferGoodsWithOwner(goodsId, toAddress, account, currentOwner);
            } else {
                receipt = goodsService.transferGoods(goodsId, toAddress);
            }
            
            result.put("success", true);
            result.put("txHash", receipt.getTransactionHash());
        } catch (Exception e) {
            System.err.println("转移商品失败: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "转移商品失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除商品
     */
    @PostMapping("/remove")
    public Map<String, Object> removeGoods(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            BigInteger goodsId = new BigInteger(params.get("goodsId"));
            String account = params.get("account"); // 获取用户指定的账户
            
            TransactionReceipt receipt;
            if (account != null && !account.isEmpty()) {
                receipt = goodsService.removeGoods(goodsId, account);
            } else {
                receipt = goodsService.removeGoods(goodsId);
            }
            
            result.put("success", true);
            result.put("txHash", receipt.getTransactionHash());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除商品失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 重置商品ID
     */
    @PostMapping("/reset")
    public Map<String, Object> resetGoodsId(@RequestBody(required = false) Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String account = params != null ? params.get("account") : null; // 获取用户指定的账户
            
            TransactionReceipt receipt;
            if (account != null && !account.isEmpty()) {
                receipt = goodsService.resetGoodsId(account);
            } else {
                receipt = goodsService.resetGoodsId();
            }
            
            // 从事件中提取新旧ID
            Map<String, BigInteger> idInfo = goodsService.getGoodsIdFromResetEvent(receipt);
            
            result.put("success", true);
            result.put("txHash", receipt.getTransactionHash());
            result.put("oldId", idInfo.get("oldId").toString());
            result.put("newId", idInfo.get("newId").toString());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "重置商品ID失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 获取所有可用账户
     */
    @GetMapping("/accounts")
    public Map<String, Object> getAllAccounts() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, String> accounts = goodsService.getAllAccounts();
            result.put("success", true);
            result.put("accounts", accounts);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取账户列表失败: " + e.getMessage());
        }
        return result;
    }

    @GetMapping("/api/system/save-records")
    public ResponseEntity<Map<String, Object>> saveRecords() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            transferTimeService.triggerSave();
            result.put("success", true);
            result.put("message", "时间记录数据已成功保存");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存时间记录数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取商品列表
     */
    @GetMapping("/api/goods/list")
    public Map<String, Object> getGoodsList(@RequestParam("account") String account) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取所有存在的商品
            List<Map<String, Object>> goodsList = new ArrayList<>();
            int maxIdToTry = 30; // 默认尝试30个ID
            
            for (int i = 0; i < maxIdToTry; i++) {
                try {
                    // 获取商品，并转换为Map以保持一致性
                    GoodsInfo goodsInfo = goodsService.getGoods(BigInteger.valueOf(i), account);
                    if (goodsInfo != null) {
                        // 将GoodsInfo转换为Map
                        Map<String, Object> goodsMap = new HashMap<>();
                        goodsMap.put("id", goodsInfo.getId().toString());
                        goodsMap.put("name", goodsInfo.getName());
                        goodsMap.put("description", goodsInfo.getDescription());
                        goodsMap.put("owner", goodsInfo.getOwner());
                        goodsMap.put("historyOwners", goodsInfo.getHistoryOwners());
                        goodsMap.put("createTime", goodsInfo.getCreateTime());
                        goodsMap.put("ownershipTimestamps", goodsInfo.getOwnershipTimestamps());
                        
                        goodsList.add(goodsMap);
                    }
                } catch (Exception e) {
                    // 忽略不存在的商品
                    System.out.println("商品ID " + i + " 不存在或已删除");
                }
            }
            
            result.put("success", true);
            result.put("goods", goodsList);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取商品列表失败: " + e.getMessage());
        }
        
        return result;
    }
} 